﻿using System;

using System.Collections.Generic;
using System.Text;

namespace Silvermoon.Controls.Base
{
    public abstract class ButtonBase : NotifyEventControl
    {
        private bool isPressed;
        private bool toggle;
        private bool isDown;

        public virtual bool Toggle { get { return toggle; } set { toggle = value; } }

        public bool IsDown { get { return isDown; } set { if (isDown != value) { isDown = value; OnDownChanged(); } } }

        public bool IsDownOrPressed { get { return isDown | isPressed; } }

        public bool IsPressed
        {
            get { return isPressed && Enabled; }
            set
            {
                if (isPressed != value)
                {
                    isPressed = value;
                    OnPressedChanged();
                    Invalidate(InvalidationFlag.Appearance);
                }
            }
        }

        public override void OnMouseDown(MouseDownEventArgs e)
        {
            if (!e.Handled)
            {
                e.Handled = true;
                if (Enabled) IsPressed = true;
            }
            base.OnMouseDown(e);
        }

        public override void OnMouseUp(MouseUpEventArgs e)
        {
            if (!e.Handled)
            {
                e.AllowDoubleClick = false;
            }
            IsPressed = false;
            e.Handled = true;

            base.OnMouseUp(e);
        }

        protected override void OnClick()
        {
            if (Enabled)
            {
                if (toggle) IsDown ^= true;
                base.OnClick();
            }
        }

        public void PerformClick()
        {
            OnClick();
        }

        protected virtual void OnDownChanged()
        {
            if (DownChanged != null) DownChanged(this, EventArgs.Empty);
            Invalidate(InvalidationFlag.Appearance);
        }

        protected virtual void OnPressedChanged()
        {

            if (PressedChanged != null) PressedChanged(this, EventArgs.Empty);

        }

        public override bool CanFocus
        {
            get
            {
                return false;
            }
        }

        #region Events

        public event EventHandler PressedChanged;
        public event EventHandler DownChanged;

        #endregion
    }
}


